package com.feng.oauth2;

import com.alibaba.fastjson.JSON;
import com.feng.oauth2.oauth.domain.dto.OauthClientDetailsDto;
import com.feng.oauth2.oauth.domain.dto.UserFormDto;
import com.feng.oauth2.oauth.domain.dto.UserJsonDto;
import com.feng.oauth2.oauth.domain.oauth.OauthClientDetails;
import com.feng.oauth2.oauth.service.OauthService;
import com.feng.oauth2.oauth.service.UserService;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.net.ssl.SSLContext;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;


/**
 * @author feng
 * @description TODO
 * @date 2019/1/10 16:58
 */
@Controller
@RequestMapping("api")
public class TestController2 {

    Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserService ouathUserService;
    @Autowired
    private OauthService oauthService;
    @ResponseBody
    @GetMapping("test")
    public  String get(){
        //        //
        OauthClientDetailsDto dto1 = new OauthClientDetailsDto();
        dto1.setArchived(true);
        oauthService.registerClientDetails(dto1);
        UserFormDto dto = new UserFormDto();
        dto.setPassword("123456");
        dto.setUsername("123456");
        dto.setPhone("123456789011");
        dto.setClientId(dto1.getClientId());
        dto.setEmail("333@qq.com");
        dto.setGuid(UUID.randomUUID().toString());

        ouathUserService.saveUser(dto);

//        System.out.println(JSON.toJSONString( ouathUserService.findByClientId("1aeb96fdffff001148ed10bc13c04329") ));;
        return "success";
    }

    @RequestMapping("test2")
    public String getOauthCode1(@RequestParam(required=true)String clientId, @RequestParam(required=true)String redirectUri,@RequestParam(required=true)String errorUri,Model model) {
        StringBuffer srb = new StringBuffer();
        UserJsonDto ujd = null;
        try {

            ujd = ouathUserService.findByClientId(clientId);
            OauthClientDetails ocd = oauthService.loadOauthClientDetails(clientId);
            String codeUri = redirectUri;
            srb.append("http://127.0.0.1:8080").append("/oauth/authorize?").append("response_type=code")
                    .append("&client_id="+clientId)
                    .append("&redirect_uri="+URLEncoder.encode(codeUri,"utf-8"))
                    .append("&scope=read")
                    .append("&state=1234567");

            SSLContext sslcontext = HttpClientUtil.createIgnoreVerifySSL();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext,new AllowAllHostnameVerifier()))
                    .build();

            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).setHostnameVerifier(new AllowAllHostnameVerifier()).build();


            HttpResponse response = null;
            //先登录oauht2
            HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/api/login?username="+ujd.getUsername()+"&password="+clientId+ujd.getUsername()+clientId);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setRedirectsEnabled(false).setAuthenticationEnabled(true).build();
            httpPost.setConfig(requestConfig);
            //获取code
            HttpPost  httpPost2 = new HttpPost(srb.toString());
            httpPost2.setConfig(requestConfig);
            //code重定向前，需要通过授权
            HttpPost  httpPost3 = new HttpPost("http://127.0.0.1:8080/oauth/authorize?user_oauth_approval=true");
            httpPost3.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            log.debug("response.getStatusLine().getStatusCode()1===================>"+response.getStatusLine().getStatusCode());
            if(response.getStatusLine().getStatusCode() == HttpStatus.FOUND.value()){
                response = httpClient.execute(httpPost2);
                log.debug("response.getStatusLine().getStatusCode()2===================>"+response.getStatusLine().getStatusCode());
                if(response.getStatusLine().getStatusCode() == HttpStatus.OK.value()){
                    System.out.println("================================================");
                    System.out.println(EntityUtils.toString(response.getEntity(),"utf-8"));
                    System.out.println("================================================");
                    response = httpClient.execute(httpPost3);
                    log.debug("response.getStatusLine().getStatusCode()3===================>"+response.getStatusLine().getStatusCode());
                    if(response.getStatusLine().getStatusCode() == HttpStatus.FOUND.value() || response.getStatusLine().getStatusCode() == HttpStatus.OK.value()){
                        Header header3 = response.getFirstHeader("Location");
                        String location3 = header3.getValue();
                        log.info("返回code码给指定的路径"+location3);
                        return "redirect:"+location3;
                    }else {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            //按指定编码转换结果实体为String类型
                            String returnstr = EntityUtils.toString(entity,"utf-8");
                            log.info("oauth2授权失败，返回的数据"+returnstr);
                        }
                        throw  new Exception("oauth2授权失败");
                    }

                }else if(response.getStatusLine().getStatusCode() == HttpStatus.FOUND.value()){
                    Header header4 = response.getFirstHeader("Location");
                    String location4 = header4.getValue();
                    log.info("返回code码给指定的路径location4========>>>"+location4);
                    return "redirect:"+location4;
                }else{
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        //按指定编码转换结果实体为String类型
                        String returnstr = EntityUtils.toString(entity,"utf-8");
                        log.info("oauth2获取code失败，返回的数据"+returnstr);
                    }
                    throw new Exception("认证失败");
                }
            }else{
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    //按指定编码转换结果实体为String类型
                    String body = EntityUtils.toString(entity,"utf-8");
                    log.info("oauth2登录失败，返回的数据"+body);
                }
                throw new Exception("认证失败");
            }
        } catch (Exception e) {
            log.error("系统错误",e);
            try {
                return "redirect:"+errorUri+"?error="+ URLEncoder.encode("系统异常","utf-8");
            } catch (UnsupportedEncodingException e1) {
                log.error("编码错误",e1);
            }
        }
        return null;
    }

    @RequestMapping("/test3")
    public String test3(){

        System.out.println("(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((");

        return "hello world !";
    }
}
